package com.sdtele.tta.operation;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.sdtele.tta.dac.Dac;
import com.sdtele.tta.models.JsonRequest;
import com.sdtele.tta.models.JsonResponse;
import com.sdtele.tta.models.User;
import com.sdtele.tta.models.VoteOperation;
import com.sdtele.tta.models.VoteOption;
import com.sdtele.tta.models.VoteScore;
import com.sdtele.tta.models.VoteTask;

/**
 * 操作类实现：GetUser(json.operation=getUser)
 * 
 * @author XCream
 */
public class OperationAddVoteScore extends Operation {

	@Override
	public JsonResponse handle(JsonRequest jsonRequest) {
		JsonResponse jres = new JsonResponse();
		User curUser = (User) request.getSession().getAttribute("user");
		long voteId = jsonRequest.getJsonObject().get("voteId").getAsLong();
		JsonArray opArray =  jsonRequest.getJsonObject().get("results").getAsJsonArray();
		
		for (int i = 0; i < opArray.size(); i++) {
			long voteOptionId = opArray.get(i).getAsJsonObject().get("voteOptionId").getAsLong();
			int score = opArray.get(i).getAsJsonObject().get("voteScore").getAsInt();
			VoteScore voteScore = new VoteScore();
			voteScore.setUserId(curUser.getId());
			voteScore.setVoteId(voteId);
			voteScore.setVoteOptionId(voteOptionId);
			voteScore.setScore(score);
			Dac.getInstance().addVoteScore(voteScore);
			if (voteScore.getId() > 0) {
				
				jres.setStatus(0);
				jres.setMessage("添加投票成绩成功");
				jres.setEntity(voteScore);
			} else {
				jres.setStatus(1);
				jres.setMessage("添加投票成绩失败");
			}

		}
		if(Dac.getInstance().getVotescore(voteId).size()>0) {
		VoteOperation voteOperation = Dac.getInstance().getVoteOperation(voteId, curUser.getId());
		System.out.println(voteOperation);
		voteOperation.setCompletion(1);
		Dac.getInstance().chgVoteoperation(voteOperation);

		int voteSize = 0;
		List<VoteOperation> opSize = Dac.getInstance().getVoteTaskSizebysloved(voteId);
		if (opSize != null) {
			voteSize = opSize.size();
		} else {
			voteSize = 0;
		}
		
		int voteSloveSize = 0;
		List<VoteOperation> voteSizeofSloved = Dac.getInstance().getVoteTaskSize(voteId);
		if (voteSizeofSloved != null) {
			voteSloveSize = voteSizeofSloved.size();
		} else {
			voteSloveSize = 0;
		}
		String vote = voteSize + "/" + voteSloveSize;
		VoteTask votetask = Dac.getInstance().getVoteTaskbyVoteid(voteId);
		votetask.setCompletion(vote);
		if (Dac.getInstance().chgVoteTask(votetask)) {
			jres.setStatus(0);
			jres.setMessage("更改投票任务完成度成功");
		} else {
			jres.setStatus(1);
			jres.setMessage("更改投票任务完成度失败");
		}
	}
		return jres;
	}

}